import time
import snowflake.client
from flask import jsonify
from views.base import BaseHandler
from db import db
import json,requests
from util.myredis import r
from views.usercode import SmsCode


def create_ordercode(tablename,count):
    # 生成唯一ID
    code = snowflake.client.get_guid()
    # 用redis解决始终回拨，根据key查询上一次存入的结果，
    # 和当前生成的对比，如果当前小于redis中存储的，说明发生时钟回拨
    value = r.get_str(tablename)
    if value:
        if int(code) < int(value):
            create_ordercode(tablename,count)
    # 把最后一次生成的存入redis
    r.set_str(tablename,code)
    # 取模获取到表
    number = hash(code)%(count)
    if number == 0:
        return tablename,code
    else:
        return tablename + str(number),code


class LandmarkHandler(BaseHandler):
    def post(self):
        # 获取页面参数
        data = json.loads(self.request.body)
        descrip = data['descrip']
        purpose = data['purpose']
        tmoney = int(data['tmoney'])
        pay_type = int(data['pay_type'])
        interest_rate = float(data['interest_rate'])
        term = int(data['term'])
        userid = int(data["userid"])
        # 生成code，雪花算法生成code
        tablename, code = create_ordercode('landmarks', 3)
        print(">>",tablename,code)
        # 加入表的标
        sql = """insert into %s(money,code,tmoney,purpose,descrip,term,pay_type,interest_rate,userid) values (%d,%d,%d,'%s','%s',%d,%d,'%s',%d)""" % (
        tablename, tmoney, int(code), tmoney, purpose, descrip, term, pay_type, interest_rate, userid)
        db.add(sql)
        db.commit()
        key = 'landmarkss'
        #以列表形式从左往右添加
        r.list_push(key,str(code))
        return self.finish({'code': 200, 'msg': "等待审核中"})


def getmes():
    #查询出审核员id
    sql = "select ad.id from admin_user ad inner join roles rs on rs.name='审核员' and ad.roleid=rs.id"
    check = db.find_all(sql)
    if not check:
        return jsonify({"code":501,"msg":"没有审核员"})
    for i in check:
        key = 'landmarkss'
        code = r.list_pop(key)
        if code != None:
            number = hash(int(code.decode())) % 3
            if number == 0:
                sqls = "update landmarks set audit_userid=%d where code=%d" % (int(i["id"]), int(code))
                db.add(sqls)
                db.commit()
                print("if标的分配成功")
            else:
                landmarks = "landmarks" + str(number)
                sql1 = "update %s set audit_userid=%d where code=%d" % (landmarks, int(i["id"]), int(code))
                db.add(sql1)
                db.commit()
        else:
            return "队列没有数据"


import datetime
class Landmarks(BaseHandler):
    def get(self):
        userid = self.get_query_argument("userid")
        page = self.get_query_argument("page")
        page_size = self.get_query_argument("page_size")
        start = (int(page)-1) * int(page_size)
        print(">>>",userid)
        sql = "select count(*) as a from (select * from landmarks where audit_userid=%d union all select * from landmarks1 where audit_userid=%d union all select * from landmarks2 where audit_userid=%d) as t" % (
        int(userid), int(userid), int(userid))
        ress = db.findone(sql)
        total = ress['a']
        sqls = "select *  from (select * from landmarks where status!=1 and audit_userid=%d union all select * from landmarks1 where status!=1 and audit_userid=%d union all select * from landmarks2 where status!=1 and audit_userid=%d) as t limit %d,%d" % (
            int(userid), int(userid), int(userid), int(start), int(page_size))
        res = db.find_all(sqls)
        for i in res:
            i["interest_rate"] = float(i["interest_rate"])
            i["code"] = str(i["code"])
        print(">>",res,total)
        return self.finish({"code": 200,"msg":"获取成功","data":res,"total":total})
    def post(self):
        code = json.loads(self.request.body)
        number = hash(int(code)) % 3
        audit_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        if number !=0:
            landmarks = "landmarks" + str(number)
            sql = "update %s set status=%d,audit_time='%s' where code=%d"%(landmarks,1,audit_time,int(code))
            db.add(sql)
            db.commit()
        else:
            sql1 = "update landmarks set status=%d,audit_time='%s' where code=%d" % (1, audit_time, int(code))
            db.add(sql1)
            db.commit()
        return self.finish({"code": 200, "msg": "审核成功"})


from util.comm import get_ali_object
class  Aa(BaseHandler):
    def get(self):
        orderno = "23424342"
        score = int(time.time())+1800
        r.sortedset_add("cancelorderlist","2342434234",score)
        r.sortedset_add("cancelorderlist",orderno,score)
        pay = get_ali_object()
         # 生成支付的url
        query_params = pay.direct_pay(
            subject="test",  # 商品简单描述
            out_trade_no=str(orderno),  # 用户购买的商品订单号（每次不一样） 20180301073422891
            total_amount=float(100.00),  # 交易金额(单位: 元 保留俩位小数)
        )
        pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
        self.write({"code": 200,'url': pay_url})


import datetime
import random
import time

from views.base import BaseHandler
import json
from db import db
from util.comm import get_ali_object
class GetPwd(BaseHandler): #获取交易密码
    def get(self):
        userid = self.get_query_argument('userid')
        sql = "select pay_password from open_bank where userid = %d"%(int(userid))
        res = db.findone(sql)
        return self.finish({'code':200,'pwd':res['pay_password']})
class Getuser(BaseHandler):
    def get(self):
        uid = self.get_query_argument('userid')
        sql = "select * from user where id=%d"%int(uid)
        res = db.findone(sql)
        money = float(res['money'])
        print(money)
        self.finish({'code': 200, 'data':money})

class Payurl(BaseHandler):
    def get(self):
        # 获取支付返回的参数
        # data = json.loads(self.request.body)3
        userid = int(self.get_query_argument('userid'))
        money = str(self.get_query_argument('pay'))
        number = str(int(time.time())) + str(userid) + str(random.randint(100000, 999999))
        pwd = self.get_query_argument('pwd')
        sqlpwd = "select pay_password from open_bank where userid=%d"%userid
        res = db.findone(sqlpwd)
        npwd = res['pay_password']
        if pwd != npwd:
            return self.finish({'code':401,'msg':'交易密码有误'})
        sql1 = "select money from user where id=%d"%userid
        res = db.findone(sql1)
        print(res)
        moneys = res['money']
        if moneys == None:
            sql = "update user set money='%s' where id=%d"%(money,userid)
        else:
            aa = int(moneys)+int(money)
            sql = "update user set money='%s' where id=%d"%(aa,userid)
        db.update(sql)
        static = 1
        create_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        sql2 = "insert into payrecord(number, uid, money, static, create_time) values ('%s',%d,'%s',%d,'%s')"%(number, userid, money, static, create_time)
        db.update(sql2)
        db.commit()
        pay_time = int(time.time()) + 1800
        r.sortedset_add('numberpay', number, pay_time)
        pay = get_ali_object()
        query_params = pay.direct_pay(
            subject=str(userid) + "充值服务",  # 商品简单描述
            out_trade_no=number,  # 用户购买的商品订单号（每次不一样） 20180301073422891
            total_amount=float(money),  # 交易金额(单位: 元 保留俩位小数)
        )
        pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
        self.write({
            'code': 200,
            'url': pay_url
        })

class Callback(BaseHandler):
    def get(self):
        trade_no = self.get_query_argument('trade_no')
        out_trade_no = self.get_query_argument('out_trade_no')  # 订单号
        try:
            sql = "update payrecord set static=2 where number='%s'"%(out_trade_no)
            db.update(sql)
            db.commit()
        except:
            db.rollback()
        self.redirect("http://localhost:8080/#/balance")



class Getlandmarks1fenye(BaseHandler):
    def get(self):
        page_size = 2
        page = int(self.get_query_argument('page'))
        static = (page-1)*page_size
        # r.del_key('Getlandmarks1fenye')
        sql = "select * from landmarks1 where status=1 union all select * from landmarks2 where status=1 union all select * from landmarks where status=1 limit %d,%d"%(static,page_size)
        res = db.find_all(sql)
        list = [{'purpose': i['purpose'], 'audit_time': str(i['audit_time']), 'money': i['money'], 'term': i['term'],"interest_rate":str(i['interest_rate']),
                 'status': i['status'], 'code': str(i['code'])} for i in res]
        # r.str_add('Getlandmarks1fenye',list)
        self.finish({'code': 200, 'data': list})

# 出借
class Getlend(BaseHandler):
    def post(self):
        data = json.loads(self.request.body)
        code = data['code']
        print(code)
        userid = data['userid']
        money = data['money']
        print("111111111111",money)
        addtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        guser = "select * from user where id=%d" % (int(userid))
        user = db.findone(guser)
        print(user)
        # 获取当前用户的金额
        pmoney = float(user['money'])
        # print(pmoney)
        umoney = int(pmoney) - int(money)
        print(umoney)
        # if re.findall('r^\d&')
        if int(money) > int(pmoney):
            return self.finish({'code':401,'msg':'金额不足'})
        number = hash(int(code))%3
        print(number)
        tablename = 'landmarks'
        if number > 0:
            tablename = tablename+str(number)
        # 查询需要借款人所有信息
        sql = "select * from "+tablename+" where code='%s'"%code
        res = db.findone(sql)
        print(res)
        # 利息
        interest = float(res['interest_rate'])
        print('interest',interest)
        # 利息加还款金额
        tmoney = money + (money*int(interest))
        print(tmoney)
        # 状态
        status =1
        # 差多钱满标
        balance = int(float(res['money'])) - int(money)
        print('*****',balance)
        landmarksmoney = int(res['money'])
        if int(money) > int(landmarksmoney):
            return self.finish({'code': 402, 'msg': '超出当前用户所借金额'})
        sql1 = "insert into invest(userid, landmarksid, money, addtime, interest, tmoney, status) values (%d,%d,'%s','%s','%s','%s',%d)"%(int(userid), int(code), money, addtime, interest, tmoney, int(status))
        db.update(sql1)
        # 修改表还剩多少钱满标
        usql = "update "+tablename+" set money='%s' where code='%s'"%(balance,code)
        db.update(usql)
        # 锁定金额
        lockmoney = user['lockmoney']
        print(lockmoney)
        lmoney = int(lockmoney) + int(money)
        usql = "update user set money='%s',lockmoney='%s' where id=%d"%(umoney,lmoney,int(userid))
        db.update(usql)
        db.commit()
        times = time.time()
        r.sortedset_add('lendlandmarks',code,times)
        self.finish({'code':200,'msg': '出借成功'})



from elasticsearch import Elasticsearch
es = Elasticsearch("http://43.138.40.106:9200/")
import math
class SearchLandmarks(BaseHandler):
    def get(self):
        sql = "select code,descrip,purpose,audit_userid from landmarks"
        res = db.find_all(sql)
        if res:
            for i in res:
                print(i)
                es.index(index="landmarks", body={
                    "id": i["code"],
                    "descrip": i["descrip"],
                    "purpose": i["purpose"],
                    "audit_userid": i["audit_userid"]
                })
        # 获取查询条件
        # descrip = self.get_query_argument("descrip")
        # page = self.get_query_argument("page")
        # page_size = 2
        # start = math.ceil((int(page)-1)*page_size)
        # wheredata = {
        #     "query": {
        #         "match": {"descrip": descrip}
        #     },
        #     "from": start,
        #     "size": page_size,
        #     "sort": {
        #         "id": {
        #             "order": "asc"
        #         }
        #     }
        # }
        # res = es.search(index="landmarks", body=wheredata)
        # data = res["hits"]["hits"]
        # list = []
        # for i in data:
        #     list.append(i["_source"])
        # print(list)


def duedata():
    # 一周后的今天
    date1 = datetime.datetime.now() + datetime.timedelta(days=7)
    # 格式化年月日
    nitme = datetime.datetime.strftime(date1, "%Y-%m-%d")
    print(date1)
    sql = "select code,userid from (select * from landmarks1 where status=4 union all select * from landmarks2 where status=4 union all select * from landmarks where status=4)t where date_format(t.audit_time,'%Y-%m-%d') ='" + nitme + "'"
    res = db.find_all(sql)
    if res:
        for i in res:
            sql1 = "select mobile from pcuser where id=%d" % (i['userid'])
            user = db.findone(sql1)
            c = SmsCode(user['mobile'])
            # c= send_message("18503829015")
            print(c)
    # 还款20
    # 现在23


def withhold():
    now = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d")
    sql = "select code,userid from (select * from landmarks1 where status=4 union all select * from landmarks2 where status=4 union all select * from landmarks where status=4)t where date_format(t.exptime,'%Y-%m-%d') ='" + now + "'"
    res = db.find_all(sql)
    print('res', res)
    if res:
        for i in res:
            # 查找所有投标的人
            sql1 = "select * from invest where landmarksid='%s'" % (i['code'])
            user = db.find_all(sql1)
            for j in user:
                # 更新所有用户投资的钱

                sql2 = "update user set money='%s' where id=%d" % (j['tmoney'], int(j['userid']))
                print(sql2)
                db.update(sql2)

                # 减还款的金额
                sql3 = "select * from user where id=%d" % (i['userid'])
                pc = db.findone(sql3)
                money = pc['money'] - j['tmoney']
                print(money)
                sql4 = "update user set money='%s' where id=%d" % (money, int(i['userid']))
                db.update(sql4)
                db.commit()
            print('还款完成')
            return '还款完成'


withhold()




